package com.ww;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

public class StudentManage {
    private final ArrayList<Student> students = new ArrayList();
    private final Scanner sc;

    public StudentManage() {
        this.sc = new Scanner(System.in);
    }

    public void addStudent() {
        System.out.print("请输入学生学号：");
        String id = this.sc.nextLine();
        if (this.getIndex(id) != -1) {
            System.out.println("该学号已被占用，请重新输入！");
        } else {
            System.out.print("请输入学生姓名：");
            String name = this.sc.nextLine();
            System.out.print("请输入学生年龄：");
            int age = this.sc.nextInt();
            this.sc.nextLine();
            System.out.print("请输入学生居住地：");
            String address = this.sc.nextLine();
            this.students.add(new Student(id, name, age, address));
            System.out.println("添加学生成功！");
        }
    }

    public void deleteStudent() {
        System.out.print("请输入要删除的学生学号：");
        String id = this.sc.nextLine();
        int index = this.getIndex(id);
        if (index == -1) {
            System.out.println("该学号不存在，请重新输入！");
        } else {
            this.students.remove(index);
            System.out.println("删除学生成功！");
        }

    }

    public void updateStudent() {
        System.out.print("请输入要修改的学生学号：");
        String id = this.sc.nextLine();
        int index = this.getIndex(id);
        if (index == -1) {
            System.out.println("该学号不存在，请重新输入！");
        } else {
            System.out.print("请输入学生新姓名：");
            String name = this.sc.nextLine();
            System.out.print("请输入学生新年龄：");
            int age = this.sc.nextInt();
            this.sc.nextLine();
            System.out.print("请输入学生新居住地：");
            String address = this.sc.nextLine();
            Student student = (Student)this.students.get(index);
            student.setName(name);
            student.setAge(age);
            student.setAddress(address);
            System.out.println("修改学生成功！");
        }

    }

    public void showAllStudents() {
        if (this.students.isEmpty()) {
            System.out.println("无信息，请先添加学生！");
        } else {
            System.out.println("学号\t\t姓名\t\t年龄\t\t居住地");
            Iterator var1 = this.students.iterator();

            while(var1.hasNext()) {
                Student student = (Student)var1.next();
                System.out.printf("%s\t\t%s\t\t%d岁\t%s\n", student.getId(), student.getName(), student.getAge(), student.getAddress());
            }

        }
    }

    private int getIndex(String id) {
        for(int i = 0; i < this.students.size(); ++i) {
            if (((Student)this.students.get(i)).getId().equals(id)) {
                return i;
            }
        }

        return -1;
    }
}
